import binascii
from pathlib import Path

from cfm.data import DataLoader, DataSaver
from cfm.form import *
from cfm.service import BackendService, FrontendService

# ==================
# = Variable Alias =
# ==================

workspaceName = "workspace"
workspaceDir = Path("./workspace/")

# ===========================
# = Frontend Service Config =
# ===========================
frontendService = FrontendService(
    workspaceName = workspaceName,
    workspaceDir = workspaceDir,
    
    server_headless = False,
    server_port = 8501
)

# ===========================
# = Backend Service Config =
# ===========================
backendService = BackendService(
    workspaceName = workspaceName,
    workspaceDir = workspaceDir,
    
    server_headless = False,
    server_port = 8502
)

# ===============
# = Form Config =
# ===============
Form.add_components([
    
    TextInput(
        _saveDesc = "TextInput1",
    ),
    
    FileUploader(
        _saveDesc = "FileUploader1",
    )

])

def handler(res: list[CompResultDesc]) -> None:
    if res == []: return
    
    for desc in res:
        comp, result = desc.component, desc.result 
        
        if comp @ TextInput:
            b = result.encode("utf-8")
            DataSaver.add(
                comp._saveDesc,
                f"{len(b)}s",
                b
            )
            
        elif comp @ FileUploader:
            filename = result.name.encode("utf-8")
            DataSaver.add(
                comp._saveDesc + " filename",
                f"{len(filename)}s",
                filename
            )
            hexdata = str(binascii.hexlify(result.getvalue())).encode("utf-8")
            DataSaver.add(
                comp._saveDesc + " filedata",
                f"{len(hexdata)}s",
                hexdata
            )
            
    DataSaver.tofile(workspaceDir / "data")
    DataSaver.clear()
            
Form.set_handler(handler)
